"""
数据库会话管理模块
"""
from typing import AsyncGenerator
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker      
from config import settings
from urllib.parse import quote_plus


# 创建异步引擎
# 对密码进行URL编码，处理特殊字符
encoded_password = quote_plus(settings.POSTGRES_PASSWORD)
engine = create_async_engine(
    f"postgresql+asyncpg://{settings.POSTGRES_USER}:{encoded_password}@{settings.POSTGRES_SERVER}:{settings.POSTGRES_PORT}/{settings.POSTGRES_DB}?prepared_statement_cache_size=0",
    echo=False,  # 设置为 True 可以看到 SQL 语句
    pool_pre_ping=True,  # 连接池健康检查
    pool_size=5,  # 连接池大小
    max_overflow=10  # 最大连接溢出数
)

# 创建异步会话工厂
AsyncSessionLocal = async_sessionmaker(
    bind=engine,
    class_=AsyncSession,
    expire_on_commit=False,
    autocommit=False,
    autoflush=False
)

# 获取异步数据库会话的依赖函数
async def get_db() -> AsyncGenerator[AsyncSession, None]:
    """
    获取异步数据库会话的依赖函数
    
    Yields:
        AsyncSession: 异步数据库会话
    """
    async with AsyncSessionLocal() as session:
        try:
            yield session
        finally:
            await session.close()